﻿using BW.Rabbit.Domain;
using BW.Rabbit.ErrorCode;
using BW.Rabbit.Infrasttucture.Interfaces;
using BW.Rabbit.Read.API.Applications.Commands.GoodsInfoCommands;
using BW.Rabbit.Read.API.Dto;
using MediatR;
using Microsoft.EntityFrameworkCore.Infrastructure;
using System.Collections.Generic;
using static System.Net.Mime.MediaTypeNames;

namespace BW.Rabbit.Read.API.Applications.CommandHandlers.GoodsInfoCommandHandlers
{
    /// <summary>
    /// 商品信息查询命令处理
    /// </summary>
    public class GoodsInfoQueryCommandHandler : IRequestHandler<GoodsInfoQueryCommands, APIResult<APIPaging<GoodInfosDto>>>
    {
        /// <summary>
        /// 商品信息仓储
        /// </summary>
        IBaseRepository<GoodsInfo> goodInfoRepo;
        /// <summary>
        /// 商品仓储
        /// </summary>
        IBaseRepository<Goods> goodsRepo;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="goodsRepo">商品仓储</param>
        /// <param name="goodInfoRepo">商品信息仓储</param>
        public GoodsInfoQueryCommandHandler(IBaseRepository<Goods> goodsRepo, IBaseRepository<GoodsInfo> goodInfoRepo)
        {
            this.goodsRepo = goodsRepo;
            this.goodInfoRepo = goodInfoRepo;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public Task<APIResult<APIPaging<GoodInfosDto>>> Handle(GoodsInfoQueryCommands request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<GoodInfosDto>> result = new APIResult<APIPaging<GoodInfosDto>>();
            result.Code = EnumCode.查询成功;
            result.Msg = EnumCode.查询成功.ToString();

            var query = from a in goodInfoRepo.GetAll()
                        join b in goodsRepo.GetAll() on a.GoodsId equals b.GoodsId
                        select new GoodInfosDto
                        {
                            GoodsInfoId = a.GoodsInfoId,
                            GoodsId = a.GoodsId,
                            GoodsName = b.GoodsName,
                            Production = a.Production,
                            Guarantee = a.Guarantee,
                            LicenseNumber = a.LicenseNumber,
                            Enterprise = a.Enterprise,
                            Image = a.Image,
                            IsDel = a.IsDel,

                        };

            APIPaging<GoodInfosDto> page = new APIPaging<GoodInfosDto>();

            page.TotalCount = query.Count();

            page.PageCount = (int)Math.Ceiling(query.Count() / (double)request.PageSize);

            page.data = query.Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();

            result.Data = page;


            return Task.FromResult(result);
        }
    }
}
